package com.magic.shop.interceptor;

import com.magic.shop.constants.AuthConstants;
import com.magic.shop.constants.CommonConstants;
import com.magic.shop.constants.ZbOptions;
import com.magic.shop.vo.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.script.MagicScriptContext;

import javax.annotation.Resource;

/**
 * magic-api 接口鉴权
 * ma写的api是否需要鉴权
 *
 */
@Component
public class MagicCommonRequestInterceptor implements RequestInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(MagicCommonRequestInterceptor.class);
    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context,
                            MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {

        //String accessToken = request.getHeader(AuthConstants.ACCESS_TOKEN);
        String[] parameterValues = request.getParameterValues(AuthConstants.ACCESS_TOKEN);
        String accessToken=(parameterValues==null||parameterValues[0]==null)?null:parameterValues[0];
        //接口需要登录
        if ("true".equals(info.getOptionValue(ZbOptions.REQUIRE_LOGIN.getValue()))) {//MA原生：Options
            if(StringUtils.isBlank(accessToken)){
                return new CommonResult<>(9999, "用户未登录");
            }
            String user = stringRedisTemplate.opsForValue().get(CommonConstants.USER_LOGIN_PREFIX + accessToken);
            if (user == null) {
                //return new JsonBean<>(9999, "用户未登录");//原生
                return new CommonResult<>(9999, "用户未登录");
            }
        }
        //接口需要鉴权
        if ("true".equals(info.getOptionValue(ZbOptions.REQUIRE_API_AUTH.getValue()))) {
            if(StringUtils.isBlank(accessToken)){
                return new CommonResult<>(9998, "无权限访问该接口");
            }
            //TODO 鉴权逻辑
            if (!accessToken.equals("1q2w3e4r")) {
                //return new JsonBean<>(9999, "用户未登录");
                return new CommonResult<>(9998, "无权限访问该接口");
            }
        }

        return null;

    }


    /**
     * 接口执行之后
     * @param info	接口信息
     * @param context	变量信息
     * @param value 即将要返回到页面的值
     */
    @Override
    public Object postHandle(ApiInfo info, MagicScriptContext context, Object value, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {

        return null;
    }

    @Override
    public Object postHandle(RequestEntity requestEntity, Object value) throws Exception {
        ApiInfo info = requestEntity.getApiInfo();
//
//        if ("true".equals(info.getOptionValue(MyOptions.ENCRY_RESPONSE.getValue()))) {
//            if (value instanceof ResponseEntity) {
//                return value;
//            } else if (value instanceof ResponseModule.NullValue) {
//                return null;
//            }
//            value = AESUtils.encrypt(value.toString().getBytes(StandardCharsets.UTF_8),aesKey.getBytes(StandardCharsets.UTF_8));
//            return resultProvider.buildResult(requestEntity, value);
//        }
        return RequestInterceptor.super.postHandle(requestEntity, value);
    }
    @Override
    public void afterCompletion(ApiInfo info, MagicScriptContext context, Object returnValue, MagicHttpServletRequest request, MagicHttpServletResponse response, Throwable throwable) {
        RequestInterceptor.super.afterCompletion(info, context, returnValue, request, response, throwable);
    }

}